package com.server.server_a10.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.server.server_a10.entity.Inform;
import com.server.server_a10.entity.User;
import com.server.server_a10.entity.loginSystem.LoginInf;
import com.server.server_a10.mapper.LoginMapping;
import com.server.server_a10.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.Map;

@RestController
@Api("用来登录校验")
public class LoginHandle {
    @Autowired
    UserMapper userMapper;

    @PostMapping(value = "/login")
    @ApiOperation("测试账号100001，密码123这个接口是个测试接口，如果账号密码无误，则返回登录成功信息," +
            "并存放用户的name和id至cookie中(base64格式)")
    public Inform login(@RequestBody Map<String, Object> request, HttpServletResponse response) throws JsonProcessingException {

        long id = (int) request.get("id");
        String passwd = (String) request.get("passwd");

        User user = userMapper.selectById(id);
        System.out.println(user.toString());

        if (user==null){
            return new Inform(100,"用户不存在");
        }

        Inform inform = new Inform();

        if (user.getPasswd().equals(passwd)){
            LoginInf loginInf = new LoginInf(id,user.getName(),user.getIsAdmin());

            //设置data
            inform.setCode(200);
            inform.setData(loginInf);

            //将cookie对象加入response响应
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(loginInf);

            //转base64
            String user_inf = Base64.getEncoder().encodeToString(jsonString.getBytes());

            Cookie cookie = new Cookie("user", user_inf);
            cookie.setPath("/");
            cookie.setMaxAge(3600);
            response.addCookie(cookie);

            inform.setMsg("登录成功！！！");
        }else {
            inform.setCode(101);
            inform.setMsg("账号或密码错误");
        }
        return inform;
    }
}

